package net.zoneland.knowledge.config;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import net.zoneland.knowledge.dao.PerformanceMonitorMapper;

/**
 * 定时任务配置.
 */
@Configuration
public class TimerConfig {

    private static final Logger LOGGER = LoggerFactory.getLogger(TimerConfig.class);

    @Autowired
    private PerformanceMonitorMapper performanceMonitorMapper;

    /**
     * 同步当日性能监控日志到历史表.
     */
    @Scheduled(cron = "0 0 3 * * ?")
    @SchedulerLock(name = "syncPerformanceMonitorData", lockAtMostFor = "1H", lockAtLeastFor = "30S")
    @Transactional(rollbackFor = Exception.class)
    public void syncPerformanceMonitorData() {
        LOGGER.info("start to synchronize performance monitoring data(method:syncPerformanceMonitorData)");
        // 当天0点
        final LocalDateTime localDateTimeForOp = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);

        //同步当昨日数据当历史表
        performanceMonitorMapper.syncPerformanceMonitorData(localDateTimeForOp);

        //清空昨日数据
        performanceMonitorMapper.deleteDateByTime(localDateTimeForOp);
        LOGGER.info("end synchronize performance monitoring data(method:syncPerformanceMonitorData)");
    }
}
